<template>
	<view class="langya0">
		<view class="langya1">
			<image src="@/static/images/ly.png" mode="widthFix"></image>
		</view>
		<view class="nod100">
			<text class="nod1001">设备号:</text>
			<text class="nod1002">{{ list[0].name ? list[0].name : '未连接' }}</text>
		</view>
		<view class="langya2">
			<view class="langya4">
				<view class="">欢迎体验</view>
			</view>
		</view>
		<view class="y-0-0">
			<view class="y-0">
				<image :src="yashua" mode=""></image>
			</view>
			<view class="y-0">
				<image :src="w1" mode=""></image>
			</view>
			<view class="y-0">
				<image :src="w3" mode=""></image>
			</view>
			<view class="y-0">
				<image :src="w4" mode=""></image>
			</view>
		</view>
	</view>
</template>

<script>
var that;
export default {
	data() {
		return {
			yashua: require('@/static/images/yashua.jpg'),
			w1: require('@/static/images/w2.jpg'),
			w3: require('@/static/images/w3.jpg'),
			w4: require('@/static/images/w4.jpg'),
			getUserInfo: {},
			bleAdapter: {
				available: false
			},
			list: [],
			openPass: 'PBSS',
			openPcss: 'PCSS',
			serviceId: '',
			orderAliPayObj: 'orderAliPayObj',
			deviceId: '',
			type: 1,
			payTypeNull: null
		};
	},
	onUnload: function () {
		//在页面卸载时清除定时器有时会清除不了，可在页面跳转时清除
		that.cleanDingShi();
	},
	onLoad() {
		that = this;
		that.getSetting();
	},
	onShow() {
		uni.removeStorageSync('uuids');
		// uni.removeStorageSync(that.orderAliPayObj);

		// uni.closeBluetoothAdapter({
		// 	success() {},
		// 	fail() {}
		// });
	},
	onHide() {},
	methods: {
		getSetting() {
			console.log('11111111111111111');
			wx.getSetting({
				success(res) {
					console.log('2222222222222222222222', res);
					if (res.authSetting['scope.bluetooth']) {
						// 用户没有授权蓝牙权限
						console.log('333333333333333333');
						wx.authorize({
							scope: 'scope.bluetooth',
							success() {
								console.log('4444444444444444444444444');
								// 用户同意授权
								wx.openBluetoothAdapter({
									success: function () {
										console.log('蓝牙适配器打开成功');
										that.weixinAuther();
									},
									fail: function (err) {
										if (err.errCode === 10001) {
											// 蓝牙不可用，引导用户去系统设置中开启蓝牙
											wx.showModal({
												title: '提示',
												content: '蓝牙功能未开启，请打开手机蓝牙后再试',
												showCancel: false,
												success: () => {
													// 跳转到系统蓝牙设置页面（仅支持安卓）
													if (wx.openSystemBluetoothSetting) {
														wx.openSystemBluetoothSetting();
													} else {
														// iOS设备，提示用户手动开启蓝牙
														wx.showModal({
															title: '提示',
															content: '请手动打开手机的蓝牙功能',
															showCancel: false
														});
													}
												}
											});
										}
									}
								});
							},
							fail() {
								// 用户拒绝授权
								wx.showModal({
									title: '需要蓝牙权限',
									content: '本小程序需要使用蓝牙功能，请在设置中开启蓝牙权限',
									showCancel: false,
									success: (modalSuccess) => {
										if (modalSuccess.confirm) {
											wx.openSetting({
												success: (settingSuccess) => {
													if (settingSuccess.authSetting['scope.bluetooth']) {
														// 用户在设置页授权了蓝牙权限
														console.log('用户在设置页授权了蓝牙权限');
													} else {
														// 用户在设置页没有授权蓝牙权限
														console.log('用户在设置页没有授权蓝牙权限');
													}
												}
											});
										}
									}
								});
							}
						});
					} else {
						that.weixinAuther();
					}
				}
			});
		},
		// 微信授权start
		weixinAuther() {
			// #ifdef MP-WEIXIN
			wx.login({
				success(res) {
					that.getawardDetail(res.code);
				}
			});
			// #endif
		},
		// 通过登录的code获取登录信息
		async getawardDetail(code) {
			await uni.request({
				url: 'https://nbwmd.cn/api/user/wechat/login',
				data: {
					code
				},
				header: {
					'Content-Type': 'application/json'
				},
				method: 'POST',
				success: (res) => {
					that.getUserInfo = res.data;
					console.log('获取用户登录信息====', that.getUserInfo);
					// 获取用户登录信息之后,连接蓝牙
					that.openLanYaConne();
					// TODO  看看逻辑是否需要在此调用
				}
			});
		},
		openLanYaConne() {
			that.initBLEAdP();
		},

		initBLEAdP() {
			uni.openBluetoothAdapter({
				success: (res) => {
					//已打开
					uni.getBluetoothAdapterState({
						success: (res1) => {
							that.bleAdapter.available = true;
							that.startBluetoothDevicesDiscovery();
						},
						fail(error) {
							uni.showToast({
								icon: 'none',
								duration: 2000,
								title: '查看手机蓝牙是否打开'
							});
						}
					});
				},
				fail: (err) => {
					that.list = [];
					console.log(err);
					//未打开
					uni.showToast({
						icon: 'none',
						duration: 2000,
						title: '请打开手机蓝牙'
					});
				}
			});
		},
		//开始搜索蓝牙设备
		startBluetoothDevicesDiscovery() {
			if (!that.bleAdapter.available) {
				that.initBLEAdP();
				return;
			}
			uni.startBluetoothDevicesDiscovery({
				success(res) {
					// console.log("正在搜索蓝牙设备...,启动现设备监听", res)
					uni.onBluetoothDeviceFound((devices) => {
						// console.log("启动发现设备监听", devices)
						console.log('开始重新搜索蓝牙设备==>');
						that.getBluetoothDevices();
					});
				},
				fail(e) {
					uni.showToast({
						icon: 'none',
						duration: 2000,
						title: '搜索蓝牙失败，没有给支付宝定位权限或请检查定位是否开启'
					});
					that.list = [];
					// console.log("失败原因", e)
					// console.log('搜索蓝牙失败，错误码：' + (e.errCode || e.errMsg));
				}
			});
		},
		//获取在蓝牙模块生效期间所有已发现的蓝牙设备。包括已经和本机处于连接状态的设备
		getBluetoothDevices() {
			uni.getBluetoothDevices({
				success: (res) => {
					// #ifdef MP-WEIXIN
					console.log('----微信 搜索到的全部设备7-----', res.devices);
					var alldevices = res.devices.find((obj) => obj.name.indexOf('WMD') != -1 || obj.name.indexOf('WMD') != -1);
					if (alldevices) {
						console.log('----微信 搜索到的设备-----', alldevices);
						that.list.push(alldevices);
						// 连接蓝牙的时候需要deviceId
						that.deviceId = alldevices.deviceId;
						uni.setStorageSync('uuids', alldevices.name);
						that.connectToBLE(alldevices.deviceId);
						// 获取到可以连接的设备后

						return;
					}
					// #endif
				},
				fail: (e) => {
					console.log('获取蓝牙设备错误，错误码：' + e.errCode);
				}
			});
		},

		connectToBLE(deviceId) {
			// 发现蓝牙设备后停止搜索,同时把发现设备的deviceId传入
			uni.stopBluetoothDevicesDiscovery({});
			uni.createBLEConnection({
				deviceId,
				success(e) {
					uni.showToast({
						title: '连接蓝牙成功'
					});
					that.getBLEDeviceServices();
				}
			});
		},
		//获取蓝牙的所有服务
		getBLEDeviceServices() {
			// setTimeout(() => {
			uni.getBLEDeviceServices({
				// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
				deviceId: that.deviceId,
				success: (res) => {
					console.log('获取到蓝牙所有的服务:', res);
					res.services.forEach((item) => {
						// #ifdef MP-WEIXIN
						if (item.uuid.indexOf('0000AD01') != -1 || item.uuid.indexOf('0001') != -1) {
							// 写入特征时需要serviceId
							that.serviceId = item.uuid;
							//获取特征
							that.getBLEDeviceCharacteristics();
						}
						// #endif
					});
				}
			});
			// }, 500)
		},
		//获取蓝牙特征
		getBLEDeviceCharacteristics() {
			console.log('进入特征');
			setTimeout(() => {
				uni.getBLEDeviceCharacteristics({
					// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
					deviceId: that.deviceId,
					// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
					serviceId: that.serviceId,
					success: (res) => {
						// console.log('特征getBLEDeviceCharacteristics', res)
						that.characteristics = res.characteristics;
						// console.log('特征数组', that.characteristics)
						res.characteristics.forEach((item) => {
							console.log('item---->', item);
							// #ifdef MP-WEIXIN
							if (item.uuid.indexOf('0000AD02') != -1 || item.uuid.indexOf('0003') != -1) {
								that.characteristicId = item.uuid;

								// 获取特征成功之后,就可以创建微信订单
								that.createorder();
								//利用传参的形势传给下面的 notify，这里的uuid如果都需要用到，就不用做判断了，建议使用setTimeout进行间隔性的调用此方法
								// that.notifyBLECharacteristicValueChange(item.uuid)
							}
							// #endif
						});
					},
					fail: (res) => {
						// console.log(res)
					}
				});
			}, 1000);
		},

		// 微信创建订单
		createorder() {
			let payUrl = 'https://nbwmd.cn/api/order/wechat/pay';
			uni.request({
				url: payUrl,
				data: {
					type: 1, //0开盒金额  1 激活金额
					qty: 1,
					address: '',
					latitude: '',
					longitude: '',
					device_id: that.list[0].name
				},
				header: {
					'Content-Type': 'application/json',
					token: that.getUserInfo.data.key
				},
				method: 'POST',
				success: (res) => {
					let obj = {};
					obj.trade_no = res.data.data.out_trade_no;
					obj.type = 1;
					uni.setStorageSync(that.orderAliPayObj, JSON.stringify(obj));
					console.log('微信支付成功--------------->', res);

					uni.requestPayment({
						provider: 'wxpay', // 服务提提供商
						timeStamp: res.data.data.timeStamp, // 时间戳
						nonceStr: res.data.data.nonceStr, // 随机字符串
						package: res.data.data.package,

						signType: res.data.data.signType, // 签名算法
						paySign: res.data.data.paySign, // 签名
						success: function (res) {
							// 支付成功后就去获取蓝牙特征
							// if(res.errMsg=="requestPayment:ok"){
							console.log('-----支付成功后就去获取蓝牙特征----------', res);
							that.payTypeNull = setInterval(() => {
							let value = that.getOrderInfo();
								if (value) {
									that.payType(value);
								}
							}, 1000);
							// }else{
							// 	uni.showToast({
							// 		icon:"none",
							// 		title:"支付失败"
							// 	})
							// }
						},
						fail: function (err) {
							that.cleanDingShi();
							// console.log('支付失败', err);
						}
					});
				}
			});
		},
		//写入蓝牙 这页面传入PCSS是唤醒功能
		writeBLECharacteristicValue(deviceId, serviceId, characteristicId, data = 0X11, flag = false) {
			let buffer = new ArrayBuffer(4);
							let dataView = new DataView(buffer);
							dataView.setUint8(0, 0XAA);
							dataView.setUint8(1, 0X04);
							dataView.setUint8(2, data);
							dataView.setUint8(3, 0X55);
			// console.error('ddddddddddd', that.deviceId, that.serviceId, that.characteristicId, that.ab2hex(buffer));
			uni.writeBLECharacteristicValue({
				deviceId,
				serviceId,
				characteristicId,
				value: buffer,
				success(res) {
					console.log('--开盒成功后返回数据-----------', res);
					// 此处定时器检测订单是否创建成功
				 that.closeLanYa();
				},
				fail(res) {
					console.log('写入失败不允许错误', JSON.stringify(res));
				}
			});
		},
		getOrderInfo() {
			let value = uni.getStorageSync(that.orderAliPayObj);
			return value;
		},
		// 微信授权end
		payType(data) {
			if (!data) {
				//防止重复调用
				return;
			}
			let obj = JSON.parse(data);
		
			uni.request({
				url: 'https://nbwmd.cn/api/order/getOrderInfoByOrderNo?orderNo=' + obj.trade_no,
				data: {},
				header: {
					'Content-Type': 'application/json'
				},
				method: 'GET',
				success: (res) => {
					console.log('==========payType========>>>>>>>>>>>>', res);
					// console.log('---------payType返回参数-------------------', res)
					if (res.data.code == 200) {
						// 为1时就证明已经获取到支付的订单号了,就可以启动牙刷柄
						if (res.data.data.status == 1) {
							clearInterval(that.payTypeNull);
							// 关闭蓝牙,同时跳转到下一个页面
							that.writeBLECharacteristicValue(that.deviceId, that.serviceId, that.characteristicId, 0X22, true);
							 
						}  
					}
				}
			});
		},

		closeLanYa(flag) {
				uni.navigateTo({
					url: '/pages/index/banner'
				});
				that.cleanDingShi();
		},

		//目的是保持单个线程，否则js会在变量里面控制几个或者多个线程进行，这里保证只有一个
		cleanDingShi() {
			uni.closeBluetoothAdapter({
				success() {},
				fail() {}
			});
			 
			that.payTypeNull = null;
			uni.removeStorageSync(that.orderAliPayObj);
			// console.log("定时任务已清理")
		}
		// 开机未连接：白灯闪烁；已连接：白灯常亮
	}
};
</script>

<style lang="scss" scoped>
@import './css/index.scss';
</style>
